package org.budo.poi.csv;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.budo.poi.AbstractWorkbook;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 * @see org.apache.poi.hssf.usermodel.HSSFWorkbook
 */
@Slf4j
public class CSVWorkbook extends AbstractWorkbook {
    private String columnDelimiter = ","; // 默认列分隔符

    private String rowDelimiter = "\r\n"; // 默认行分隔符

    @Override
    public Sheet createSheet(String sheetname) {
        CSVSheet sheet = new CSVSheet(sheetname);
        this.getSheets().put(sheetname, sheet);
        return sheet;
    }

    @Override
    public void write(OutputStream outputStream) throws IOException {
        Writer writer = new OutputStreamWriter(outputStream);
        Sheet sheet = this.getSheetAt(0);

        this.writeSheet_1(sheet, writer);

        writer.flush();
    }

    private void writeSheet_1(Sheet sheet, Writer writer) throws IOException {
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();
        for (int i = firstRowNum; i <= lastRowNum; i++) {
            Row row = sheet.getRow(i);

            this.writeRow_2(writer, row);

            writer.write(this.rowDelimiter);
        }
    }

    private void writeRow_2(Writer writer, Row row) throws IOException {
        short firstCellNum = row.getFirstCellNum();
        short lastCellNum = row.getLastCellNum();
        for (int j = firstCellNum; j <= lastCellNum; j++) {
            Cell cell = row.getCell(j);
            if (null != cell) {
                this.writeCell_3(writer, cell);
            } else {
                log.error("#62 writeRow_2, cell=" + cell + ", j=" + j + ", row=" + row);
            }

            writer.write(this.columnDelimiter);
        }
    }

    private void writeCell_3(Writer writer, Cell cell) throws IOException {
        String cellValue = cell.getStringCellValue();
        if (null != cellValue) {
            String val = this.cellValue_4(cellValue);
            writer.write("\"" + val + "\"");
        }
    }

    // 双引号替换
    private String cellValue_4(String cellValue) {
        return cellValue.replaceAll("\"", "\"\"");
    }
}